package com.example.administrator.waitan.tools;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import com.android.volley.toolbox.ImageLoader;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Risky on 15/10/20.
 */
public class DiskCache implements ImageLoader.ImageCache {
    private String cacheDir = "";//定义文件储存路径
    public DiskCache(){
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            File root = Environment.getExternalStorageDirectory();
            File cacheFilr = new File(root.getAbsolutePath() + "/cache");
            if (!cacheFilr.exists()){//判断cacheFilr是否存在
                cacheFilr.mkdir();//创建此文件
            }
            //如果文件夹存在,这获取路径
            cacheDir = cacheFilr.getAbsolutePath();
        }
    }
    @Override
    public Bitmap getBitmap(String url) {
        //截取到url最后一个点的后四位  为文件名字
//        url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);
        url = MD5Util.getMD5Str(url);
        return BitmapFactory.decodeFile(cacheDir + "/" + url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {//读取图片的方法
        url = MD5Util.getMD5Str(url);
        FileOutputStream fileOutputStream = null;
        try {
            //读取文件流的url
            fileOutputStream = new FileOutputStream(cacheDir + "/" + url);
            //将图片显示到组件上   jpeg为显示格式  100为质量
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,fileOutputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            if (null != fileOutputStream){
                try{
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
